package com.easylinkin.linkappapi.device.controller;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.easylinkin.linkappapi.common.model.RequestModel;
import com.easylinkin.linkappapi.common.utils.DateUtil;
import com.easylinkin.linkappapi.common.utils.excel.ExcelConstant;
import com.easylinkin.linkappapi.common.utils.excel.ExcelTools;
import com.easylinkin.linkappapi.common.utils.io.OutputStreamUtil;
import com.easylinkin.linkappapi.device.constant.DeviceConstant.GrainSize;
import com.easylinkin.linkappapi.device.dto.EnvironmentalAreaDTO;
import com.easylinkin.linkappapi.device.dto.EnvironmentalAreaStatisticsDTO;
import com.easylinkin.linkappapi.device.service.EnvironmentalAreaService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;
import site.morn.rest.RestBuilders;
import site.morn.rest.RestMessage;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;

/**
 * 环境管理
 *
 * @author Xiaoyang
 * @since 2022-09-19
 */

@RestController
@RequestMapping("/device/environmentalArea")
@Api(tags = "环境管理区域")
public class EnvironmentalAreaController {

  @Autowired
  private EnvironmentalAreaService environmentalAreaService;

  @PostMapping
  @ApiOperation("增加区域")
  public RestMessage addArea(@RequestBody EnvironmentalAreaDTO environmentalArea){
    environmentalAreaService.addArea(environmentalArea);
    return RestBuilders.successBuilder().build();
  }

  @PutMapping
  @ApiOperation("编辑区域")
  public RestMessage updateById(@RequestBody EnvironmentalAreaDTO environmentalArea){
    environmentalAreaService.updateOne(environmentalArea);
    return RestBuilders.successBuilder().build();
  }

  @DeleteMapping
  @ApiOperation("删除部位（包含批量删除）")
  public RestMessage delBatch(@RequestBody EnvironmentalAreaDTO environmentalArea) {
    Assert.notEmpty(environmentalArea.getAreaIds(), "id不能为空");
    environmentalAreaService.delBatch(environmentalArea.getAreaIds());
    return RestBuilders.successBuilder().build();
  }

  @PostMapping("tree")
  @ApiOperation("根据条件，分页(不分页)查询")
  public RestMessage queryTree(@RequestBody EnvironmentalAreaDTO environmentalArea) {
    if (null == environmentalArea.getType()){
      environmentalArea.setType(1);// 默认查询用水
    }
    List<EnvironmentalAreaDTO> record = environmentalAreaService.queryTree(environmentalArea);
    return RestBuilders.successBuilder().data(record).build();
  }

  @PostMapping("list")
  @ApiOperation("根据条件，分页(不分页)查询")
  public RestMessage queryList(@RequestBody EnvironmentalAreaDTO environmentalArea) {
    if (null == environmentalArea.getType()){
      environmentalArea.setType(1);// 默认查询用水
    }
    List<EnvironmentalAreaDTO> record = environmentalAreaService.queryList(environmentalArea);
    return RestBuilders.successBuilder().data(record).build();
  }

  /**
   * 区域环境数据统计
   * @param areaDTO
   * @return
   */
  @PostMapping("getAreaStatistics")
  @ApiOperation("区域环境数据统计")
  public RestMessage getAreaStatistics(@RequestBody EnvironmentalAreaDTO areaDTO) {
    Assert.notNull(areaDTO, "areaStatisticsQueryVO 不能为空");
    Assert.notNull(areaDTO.getType(), "类别 不能为空");
    if(null == areaDTO.getParentId()){
      areaDTO.setParentId(0);
    }
    return RestBuilders.successBuilder()
        .data(environmentalAreaService.getEnvironmentalAreaStatistics(areaDTO)).build();
  }

  /**
   * 区域环境数据趋势图
   * @param areaDTO
   * @return
   */
  @PostMapping("countAreaStatistics")
  @ApiOperation("区域环境数据趋势图")
  public RestMessage countAreaStatistics(@RequestBody EnvironmentalAreaDTO areaDTO){
    Assert.notNull(areaDTO, "waterRecordsVo 不能为空");
    Assert.notNull(areaDTO.getType(), "类别 不能为空");
    Assert.notNull(areaDTO.getParentId(), "父类别 不能为空");
    Assert.notNull(areaDTO.getStartTime(), "开始时间 不能为空");
    Assert.notNull(areaDTO.getEndTime(), "结束时间 不能为空");
    DateUtil.checkDate(GrainSize.DAY, areaDTO.getStartTime(),
        areaDTO.getEndTime());
    List<EnvironmentalAreaStatisticsDTO> areaStatisticsDTOList = environmentalAreaService
        .countAreaStatistics(areaDTO);
    return RestBuilders.successBuilder(areaStatisticsDTOList).build();
  }


  /**
   * 一级区域环境数据趋势图
   * @param requestModel
   * @return
   */
  @PostMapping("countFirstLevelAreaStatistics")
  @ApiOperation("一级区域环境数据趋势图")
  public RestMessage countFirstLevelAreaStatistics(@RequestBody RequestModel<EnvironmentalAreaDTO> requestModel){
    EnvironmentalAreaDTO areaDTO = requestModel.getCustomQueryParams();
    Assert.notNull(areaDTO.getType(), "类别 不能为空");
    Assert.notNull(areaDTO.getStartTime(), "开始时间 不能为空");
    Assert.notNull(areaDTO.getEndTime(), "结束时间 不能为空");
//    DateUtil.checkDate(GrainSize.DAY, areaDTO.getStartTime(),areaDTO.getEndTime());
    Page page = environmentalAreaService.countFirstLevelAreaStatistics(requestModel);
    return RestBuilders.successBuilder(page).build();
  }

  /**
   * 根据条件，导出用水用电报表
   */
  @PostMapping("export")
  @ApiOperation("导出用水用电报表")
//  @CommonOperateLogAnnotate(module = LogConstant.LogModule.LABOR_MANAGEMENT, desc = "导出花名册")
  public void export(@RequestBody RequestModel<EnvironmentalAreaDTO> requestModel, HttpServletRequest request, HttpServletResponse response) {
    requestModel.getPage().setSize(-1);
    EnvironmentalAreaDTO areaDTO = requestModel.getCustomQueryParams();
    Assert.notNull(areaDTO.getType(), "类别 不能为空");
    Assert.notNull(areaDTO.getStartTime(), "开始时间 不能为空");
    Assert.notNull(areaDTO.getEndTime(), "结束时间 不能为空");

    Page  iPage = environmentalAreaService.countFirstLevelAreaStatistics(requestModel);
//    iPage.getRecords().forEach(r ->{
//
//    });
    //获取类型
    Integer type = areaDTO.getType();
    String keyValue = "日期:refDate,用水量/t:todayValue,在册人数/人:todayPeople,人均用水量/t:todayAvgValue";
    String title = "项目用水量报表";
    if (type==2){
      keyValue = "日期:refDate,用电量/kW·h:todayValue,在册人数/人:todayPeople,人均用电量/kW·h:todayAvgValue";
      title = "项目用电量报表";
    }
    String fileName = title + ".xls";
    try {
      OutputStream outputStream = OutputStreamUtil
              .getOutputStream(request, response, fileName);
      ExcelTools.exportExcel(outputStream, keyValue, iPage.getRecords(), ExcelConstant.XLS, title);
      response.flushBuffer();
      outputStream.close();
    } catch (IOException e) {
      throw new RuntimeException("excel导出失败！IOException异常" + e.getMessage());
    } catch (Exception e) {
      throw new RuntimeException("excel导出失败！" + e.getMessage());
    }
  }

  @GetMapping("initData")
  @ApiOperation("初始化数据，不要多次执行")
  public RestMessage initData(){
     environmentalAreaService.initData();
    return RestBuilders.successBuilder().build();
  }

}
